package efu.nf.like.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author lwj
 * @create 2025-10-11-15:24
 */
@Configuration
public class RedisConfig {
    /**
     * 自定义RedisTemplate，主要是自定义键值对的序列化方式
     * @param redisConnectionFactory Redis连接工厂
     * @return
     */
    @Bean
    public<T> RedisTemplate<String, T> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, T> redisTemplate = new RedisTemplate<>();

        // key序列化方式
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);

        // value序列化方式
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);

        // 配置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 创建Redis消息监听容器
     * @param redisConnectionFactory Redis连接工厂
     * @return
     */
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        return container;
    }
}